import { _decorator, Animation, CCInteger, Component, Enum, Node, ProgressBar, sp, tween, Vec3 } from 'cc';
import { GameDefine } from '../game/GameDefine';
import { StateDefine } from './StateDefine';
import { Constants, EnemyType } from '../game/Constants';
import { EffectManager } from '../game/EffectManager';
import { EventListener } from '../core/EventListener';
const { ccclass, property } = _decorator;

@ccclass('Enemy')
export class Enemy extends Component {
    public level: number = 1;   // 怪物等级
    @property({ type: sp.Skeleton, displayName: "动画组件" })
    skeleton: sp.Skeleton = null;
    @property({ type: ProgressBar, displayName: "血条" })
    hpBar: ProgressBar = null;
    @property({ type: CCInteger, displayName: "移动速度" })
    moveSpeed: number = 400;
    @property({ type: Enum(EnemyType), displayName: "敌人类型" })
    enemyType: EnemyType = EnemyType.MINION_1;

    /** 生命值 */
    @property({ type: CCInteger, displayName: "最大生命值" })
    maxHp: number = 100;
    private _curHp: number = 100;
    get curHp(): number {
        return this._curHp;
    }
    set curHp(value: number) {
        this._curHp = value;
        if (this.hpBar) {
            this.hpBar.progress = Math.max(0, Math.min(1, this._curHp / this.maxHp));
        }
    }

    @property({ type: String })
    dieAnimName: string = "die";
    isDead: boolean = false;

    /** 攻击行为 */
    canAtk: boolean = false;
    attack: number = 1;

    /** 移动行为 */
    canMove: boolean = false;
    movePos: Vec3 = new Vec3();
    private curState: StateDefine = StateDefine.idle;
    public onEnemyDid: Function | null = null;

    onLoad(): void {
        this.curHp = this.maxHp;
    }

    update(dt: number) {
        if (this.isDead || GameDefine.isGamePaused)
            return;

        // 只在x轴平滑移动，确保每帧用最新坐标
        if (this.canMove) {
            const currentX = this.node.position.x;
            const targetX = this.movePos.x;
            const dx = targetX - currentX;
            const moveStep = this.moveSpeed * dt;
            let newX = currentX;
            this.changeState(StateDefine.walk);
            if (Math.abs(dx) <= moveStep) {
                newX = targetX;
                this.canMove = false;
                this.canAtk = true;
            } else {
                newX = currentX + moveStep * Math.sign(dx);
            }
            this.node.setPosition(newX, this.node.position.y, this.node.position.z);
        }

        // 攻击英雄
        if (this.canAtk) {
            this.tryAttack();
        }
    }

    /** 秒杀敌人 */
    public killEnemy() {
        if (this.isDead)
            return;

        if (this.enemyType === EnemyType.BOSS) {
            this.onAttack(this.maxHp / 40);
            const worldPos = this.node.getWorldPosition();
            worldPos.y += 100;
            EffectManager.Instance.playCoinEffect(worldPos, () => {
                GameDefine.goldNum += 50 * this.level;
            });
            return;
        } else {
            tween(this.hpBar)
                .to(0.1, { progress: 0 })
                .call(() => {
                    this.onDead();
                })
                .start();
        }
    }

    /** 移动到攻击位置 */
    public moveToAttackPos(pos: Vec3) {
        this.canMove = true;
        this.movePos = pos;
    }

    /** 受到攻击 */
    public onAttack(damage: number) {
        // console.log(`${this.node.name} 受到攻击 ${damage}`);
        this.curHp = this.curHp - damage;
        if (this.curHp < 0) {
            this.curHp = 0;
            this.onDead();
        }
    }

    /**
     * 触发攻击（带间隔限制）
     */
    public tryAttack() {
        this.changeState(StateDefine.atk, true);
    }

    /**
     * 死亡处理
     */
    private onDead() {
        this.isDead = true;
        this.canMove = false;
        this.hpBar.node.active = false;
        this.onEnemyDid?.(this);

        // 播放金币掉落动画
        EffectManager.Instance.playCoinEffect(this.node.getWorldPosition(), () => {
            GameDefine.goldNum += 50 * this.level;
        });

        this.changeState(StateDefine.die, false, () => {
            this.node.destroy();
        });

        if (this.enemyType === EnemyType.BOSS) {
            this.scheduleOnce(() => {
                GameDefine.isGameOver = true;
                EventListener.emit('game_win');
            }, 1.5)

        }
    }

    /**
     * 状态切换，支持动画播放完成回调
     * @param newState 新状态
     * @param wrapMode 1:播放一次 2:循环播放
     * @param onFinished 动画播放完成回调
     */
    private changeState(newState: StateDefine, loop: boolean = true, onFinished?: () => void) {
        // 角色已死亡
        if (this.curState === StateDefine.die)
            return;

        // 播放相同动画
        if (this.curState === newState)
            return;

        this.curState = newState;
        let animName = '';
        switch (newState) {
            case StateDefine.idle:
                animName = 'idle';
                break;
            case StateDefine.walk:
                animName = 'move';
                break;
            case StateDefine.atk:
                animName = 'attack';
                break;
            case StateDefine.die:
                animName = this.dieAnimName;
                break;
            default:
        }

        if (this.skeleton && animName) {
            if (loop) {
                this.skeleton.setCompleteListener(() => {
                    onFinished?.();
                });
            }
            this.skeleton.setAnimation(0, animName, loop);
        }
    }
}


